using System;
using System.Collections.Generic;

namespace Randomize.Core.Generators
{
    public class CollectionGenerator<TCollectionItem> : Generator<IEnumerable<TCollectionItem>>, ICollectionGenerator
    {
        private readonly IGenerator<TCollectionItem> _itemGenerator;

        private const int DefaultMaxCount = 100;

        public int? MaxCount { get; set; }

        public int? MinCount { get; set; }

        public int? Count { get; set; }

        public CollectionGenerator(Random random, IGenerator<TCollectionItem> itemGenerator) : base(random)
        {
            _itemGenerator = itemGenerator;
            this.MinCount = 1;
            this.MaxCount = 100;
        }

        protected override IEnumerable<TCollectionItem> GenerateRandomValue()
        {
            int count = this.GetCollectionCount();
            for (int i = 0; i < count; i++)
            {
                yield return _itemGenerator.Generate();
            }
        }

        private int GetCollectionCount()
        {
            if (this.Count.HasValue)
            {
                return this.Count.Value;
            }

            int max = this.MaxCount ?? DefaultMaxCount;
            int min = this.MinCount ?? 1;

            return this.RandomInstance.Next(min, max);
        }
    }
}